package com.yxjx.duoxue.payment;

import java.io.IOException;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.nfc.cardemulation.OffHostApduService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.datamodel.DMOrder;
import com.yxjx.duoxue.datamodel.DMProduct;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class OrderInfoActivity extends BaseActionBarActivity {
	
	private static final int REQ_CODE_REFUND = 1;
	
	public static final int RESULT_CODE_PAY_SCHOOL = 101;
	public static final int RESULT_CODE_REFUND_OK = 102;
	
	private static final int MSG_LOAD_INFO_DONE = 1;
	private static final int MSG_PAY_DONE = 2;
	
	private ProgressDialog dialog;
	private DMOrder mOrder;
	
	private static final int STATUS_REUNABLE = 9;
//	1    交易创建    下订单未支付
//	2    支付成功    支付完成(包含可退款)
//	3    交易关闭    取消订单
//	4    交易完成    交易完成
//	9    资金保护期  可退款状态(7天退款)
//	10   退款中      退款中
//	11   已退款      已退款
//	12   退款失败    退款失败
//	13   主动结账    订单中主动结账给机构
//	14   自动结账    保护期到期，自动结账
//	15   核销结账    学校核销后结账（有保护期的除外）

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		orderId = (String) getIntent().getExtras().getString(Yx.KEY_ORDER_ID);
		
		setContentView(R.layout.fragment_order_info);
		findViewById(R.id.scrollView1).setVisibility(View.INVISIBLE);
		findViewById(R.id.head_item).findViewById(R.id.short_divider).setVisibility(View.INVISIBLE);
		customizeActionBarTitle("订单详情");
//		dialog = MyProgressDialog.showFullWindow(this, "", "加载中...");
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(OrderInfoActivity.this);
				JSONObject params = new JSONObject();
				try {
					params.put("id", orderId);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				DMOrder order = null;
				try {
					order = UserReg.requestOrderInfo(ulRsp, params, OrderInfoActivity.this);
					Message msg = mHandler.obtainMessage(MSG_LOAD_INFO_DONE, order);
					mHandler.sendMessage(msg);
					return;					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				Message msg = mHandler.obtainMessage(MSG_LOAD_INFO_DONE, order);
				mHandler.sendMessage(msg);
				return;
				
			}
		}).start();
	}
	
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOAD_INFO_DONE:
				if (msg.obj != null) {
					mOrder = (DMOrder) msg.obj;
					initHead();
					fillSheet();
					findViewById(R.id.scrollView1).setVisibility(View.VISIBLE);
				} else {
					UIHelper.showTips(findViewById(R.id.scrollView1), "加载失败");
				}
				dismissDialogInternal();
				break;
			case MSG_PAY_DONE:
				ResponseObject code = (ResponseObject) msg.obj;
				if (code.getCode() == MsgCode.SUCCESS) {
					UIHelper.showTips(findViewById(R.id.scrollView1), "成功付款给机构");
					// TODO notify list change pay school OK
					Intent bundle = new Intent();
					mOrder.setOrderStatusDes("交易完成");
					bundle.putExtra(Yx.KEY_ORDER_OBJECT, mOrder);
					setResult(RESULT_CODE_REFUND_OK, bundle);
					mOrder.setOrderStatus(4);
					updateActionButtons();
					UIHelper.setText((TextView) findViewById(R.id.order_info_status), "交易完成");
				} else {
					UIHelper.showTips(findViewById(R.id.scrollView1), MsgCode.descFor(code));
				}
				dismissDialogInternal();
				break;
			default:
				break;
			}
		};
	};
	private String orderId;
	
	private void dismissDialogInternal() {
		findViewById(R.id.root).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	private void initHead() {
		// head
		View item = findViewById(R.id.head_item);
		final DMCourse course = mOrder.getCourse();
		CourseListActivity.customizeCourseItem(item, course);
		
		item.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.putExtra(NwUtils.KEY_ID, "" + course.getCourseId());
				intent.setClass(getApplicationContext(), CourseIntroductionActivity.class);
				startActivity(intent);
			}
		});
	}

	private void customizeCourseItem(View item, final DMCourse course) {
		UIHelper.setText(item, R.id.course_name, course.getCourseName());
		((RatingBar) item.findViewById(R.id.rating_bar)).setRating(Float
				.valueOf(course.getCourseCommentLevel().getAvgTotalLevel()));
		UIHelper.setText(item, R.id.school_name, course.getSchoolFullName());
		int supportBook = course.getSupportBook();
		item.findViewById(R.id.free_auditon).setVisibility(
				supportBook == 1 ? View.VISIBLE : View.GONE);
		UIHelper.asyncLoadImage((ImageView) item.findViewById(R.id.icon),
				course.getHeadImageUrl(), R.drawable.default_icon);
		((TextView) item.findViewById(R.id.visit_count))
				.setText(Utils.getStyleString(course.getCourseCommentLevel()
						.getVisitCount()));
		((TextView) item.findViewById(R.id.location_info))
				.setText("");
		//Utils.getDistanceDesc(getApplicationContext(),course.getSchoolGps())
		Utils.addLabels((ViewGroup) item.findViewById(R.id.labels),
				course.getAuthArray());
	}
	
	private void fillSheet() {
		TextView tv = ((TextView) findViewById(R.id.order_info_title));
		tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        tv.setText(mOrder.getProductName());
        
		UIHelper.setText((TextView) findViewById(R.id.order_info_id), mOrder.getId());
		UIHelper.setText((TextView) findViewById(R.id.order_id_code), mOrder.getIdCode());
		UIHelper.setText((TextView) findViewById(R.id.order_info_time), Utils.getTimeStamp(mOrder.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
		UIHelper.setText((TextView) findViewById(R.id.order_info_total_price), getPayNum());
		UIHelper.setText((TextView) findViewById(R.id.order_info_contact), mOrder.getContactName());
		UIHelper.setText((TextView) findViewById(R.id.order_info_phone), mOrder.getContactPhone());
		String orderStatus = mOrder.getOrderStatusDes();
		UIHelper.setText((TextView) findViewById(R.id.order_info_status), UIHelper.isEmpty(orderStatus) ? "订单状态未知" : orderStatus);
		
		updateActionButtons();
	}

	private String getPayNum() {
		int totalPrice = mOrder.getTotalPrice();
		int payPrice = mOrder.getPayPrice();
		int offPrice = totalPrice - payPrice;
		if (offPrice <= 0) {
			return payPrice + "元";
		} else {
			return totalPrice + "元 － " + offPrice + "元代金劵 = " + payPrice + "元"; 
		}
	}
	
	public void paySchool(final View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("确定结账付款给学校吗？");
		builder.setMessage("结账给学校之后，资金将脱离多学的保护期；如遇退款只能与学校进行协商");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				paySchoolInternal(view);
			}
			
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				
			}
		});
		builder.show();
	}

		
	private void paySchoolInternal(View view) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(OrderInfoActivity.this);
				JSONObject params = new JSONObject();
				try {
					params.put("orderId", mOrder.getId());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ResponseObject code = new ResponseObject(-1, "");
				try {
					code = UserReg.requestPaySchool(ulRsp, params, OrderInfoActivity.this);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Message msg = mHandler.obtainMessage(MSG_PAY_DONE, code);
				mHandler.sendMessage(msg);
			}
		}).start();
	}
	
	public void requestRefund(final View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("确定要申请退款吗");
		builder.setMessage("申请退款后，你将无法在学校报名成功，如果已经在学习，申请退款后将无法继续学习");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				requestRefundInternal(view);
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				
			}
		});
		builder.show();
	}
	
	private void requestRefundInternal(View view) {
		Intent intent = new Intent(getApplicationContext(), RefundRequestActivity.class);
		intent.putExtra(Yx.KEY_ORDER_OBJECT, mOrder);
		startActivityForResult(intent, REQ_CODE_REFUND);
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		switch (arg0) {
		case REQ_CODE_REFUND:
			if (arg1 == RESULT_OK) {
				mOrder.setOrderStatus(10);
				mOrder.setOrderStatusDes("退款中");
				UIHelper.setText((TextView) findViewById(R.id.order_info_status), "退款中");
				updateActionButtons();
				// notify list change
				Intent bundle = new Intent();
				bundle.putExtra(Yx.KEY_ORDER_OBJECT, mOrder);
				setResult(RESULT_CODE_REFUND_OK, bundle);
			}
		}
	}

	private void updateActionButtons() {
		boolean refundable = (mOrder.getOrderStatus() == STATUS_REUNABLE);
		findViewById(R.id.order_info_buttons).setVisibility(refundable ? View.VISIBLE : View.GONE);
//		findViewById(R.id.order_info_status).setVisibility(refundable ? View.INVISIBLE : View.VISIBLE);
		findViewById(R.id.order_info_refundable).setVisibility(refundable ? View.VISIBLE : View.INVISIBLE);
	}
	
	private void dismissDialog() {
		findViewById(R.id.root).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	public void showProductInfo(View view) {
		DMProduct product = new DMProduct();
		product.setProductName(mOrder.getProductName());
		product.setId(mOrder.getProductId());
		
		Intent intent = new Intent(this,
				ProductInfoActivity.class);
		intent.putExtra(ProductInfoActivity.HIDE_BUY_BUTTON, true);
		intent.putExtra(Yx.KEY_PRODUCT_OBJECT, product);
		startActivity(intent);
	}
}
